<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="新增实例"
    width="800"
    :destroy-on-close="true"
  >
    <el-form :model="form">
      <el-form-item label="实例名称" :label-width="formLabelWidth">
        <el-input
          v-model="form.name"
          placeholder="请填写实例名称"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="实例端口" :label-width="formLabelWidth">
        <el-input
          v-model="form.port"
          placeholder="请填写端口"
          autocomplete="off"
        />
      </el-form-item>
      <!-- <el-form-item label="ue工程" :label-width="formLabelWidth">
        <el-select
          v-model="form.projectId"
          placeholder="请选择ue工程"
          @change="selectUefile"
        >
          <el-option
            v-for="item in uefiles"
            :key="item._id"
            :label="'节点：' + item.clusterHost + '    工程名称：' + item.name"
            :value="item._id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="集群节点" :label-width="formLabelWidth">
        <el-select
          v-model="currentCluster"
          placeholder="请选择节点"
          @change="selectClusterNode"
        >
          <el-option
            v-for="item in clusterNodes"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="ue工程" :label-width="formLabelWidth">
        <el-select
          v-model="form.projectId"
          placeholder="请先选择集群节点，后选择ue工程"
          @change="selectUefile"
        >
          <el-option
            v-for="item in uefiles"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否使用https协议" :label-width="formLabelWidth">
        <el-switch v-model="form.useHttps" />
      </el-form-item>
      <el-form-item
        label="https key文件"
        :label-width="formLabelWidth"
        v-show="form.useHttps"
      >
        <el-input
          v-model="form.httpsKeyFile"
          placeholder="请填写服务器中key文件路径"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="https cert文件"
        :label-width="formLabelWidth"
        v-show="form.useHttps"
      >
        <el-input
          v-model="form.httpsCertFile"
          placeholder="请填写服务器中cert文件地址"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="是否开启中继服务" :label-width="formLabelWidth">
        <el-switch v-model="form.useRelay" />
        <el-button
          v-if="form.useRelay"
          type="primary"
          style="margin-left: 20px"
          @click="addRelay"
        >
          新增
        </el-button>
      </el-form-item>
      <div v-if="form.useRelay">
        <div class="relay" v-for="(item, index) in relays" :key="index">
          <el-button
            type="danger"
            class="relay_delete"
            @click="deleteRelay(index)"
          >
            删除
          </el-button>
          <el-form-item label="stun地址" :label-width="formLabelWidth">
            <el-input
              v-model="item.stun"
              placeholder="请填写stun地址"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="turn地址" :label-width="formLabelWidth">
            <el-input
              v-model="item.turn"
              placeholder="请填写turn地址"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="中继用户名" :label-width="formLabelWidth">
            <el-input
              v-model="item.relayUsername"
              placeholder="请填写用户名"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="中继密码" :label-width="formLabelWidth">
            <el-input
              v-model="item.relayPassword"
              placeholder="请填写密码"
              autocomplete="off"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancle">取消</el-button>
        <el-button type="primary" @click="confirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, onMounted } from 'vue';
import { useAxios } from '@/hooks/useAxios';
import { GenerateId } from '@/utils/index';

const { post } = useAxios();
// 获取ue工程列表
const clusterMap = new Map();
const clusterNodes = reactive([]);
const currentCluster = ref('');
const uefiles = reactive([]);
const getUefiles = () => {
  const data = {
    pageNo: 1,
    pageSize: -1,
  };
  post('/ueserver/getUefiles', data).then(res => {
    res.data.forEach(item => {
      if (clusterMap.has(item.clusterHost)) {
        clusterMap.get(item.clusterHost).push(item);
      } else {
        clusterMap.set(item.clusterHost, [item]);
      }
    });
    clusterNodes.length = 0;
    clusterNodes.push(...clusterMap.keys());
  });
};
onMounted(() => {
  getUefiles();
});
// 弹窗状态
const dialogFormVisible = ref(false);
const formLabelWidth = ref('140px');

const form = reactive({
  clusterHost: '',
  clusterId: '',
  name: '',
  port: null,
  projectId: '',
  projectName: '',
  projectPath: '',
  originFileId: '',
  runStatus: false,
  connectStatus: false,
  useHttps: false,
  httpsKeyFile: '',
  httpsCertFile: '',
  useRelay: false,
  relays: [],
});

const selectClusterNode = val => {
  console.log('selectClusterNode==', val);
  form.projectId = '';
  uefiles.length = 0;
  uefiles.push(...clusterMap.get(val));
};
// 选择ue工程，将名称填写至表单
const selectUefile = val => {
  const target = uefiles.find(item => item.id == val);
  console.log('target', target);
  form.projectName = target.name;
  form.projectId = target.id;
  form.projectPath = target.path;
  form.originFileId = target.fileId;
  form.clusterHost = target.clusterHost;
  form.clusterId = target.clusterId;
  console.log(form);
};
// 取消按钮
const cancle = () => {
  Object.assign(form, {
    clusterHost: '',
    clusterId: '',
    name: '',
    port: null,
    projectId: '',
    projectName: '',
    projectPath: '',
    originFileId: '',
    runStatus: false,
    connectStatus: false,
    useHttps: false,
    httpsKeyFile: '',
    httpsCertFile: '',
    useRelay: false,
    relays: [],
  });
  relays.length = 0;
  currentCluster.value = '';
  uefiles.length = 0;
  dialogFormVisible.value = false;
};
const initForm = () => {
  Object.assign(form, {
    clusterHost: '',
    clusterId: '',
    name: '',
    port: null,
    projectId: '',
    projectName: '',
    projectPath: '',
    originFileId: '',
    runStatus: false,
    connectStatus: false,
    useHttps: false,
    httpsKeyFile: '',
    httpsCertFile: '',
    useRelay: false,
    relays: [],
  });
  relays.length = 0;
  currentCluster.value = '';
  uefiles.length = 0;
};
const initCopyForm = data => {
  form.clusterHost = data.clusterHost;
  form.clusterId = data.clusterId;
  form.name = data.name + '_' + GenerateId(8);
  // form.port = data.port;
  form.projectId = data.projectId;
  form.projectName = data.projectName;
  form.projectPath = data.projectPath;
  form.originFileId = data.originFileId;
  form.runStatus = false;
  form.connectStatus = false;
  form.useHttps = data.useHttps;
  form.httpsKeyFile = data.httpsKeyFile;
  form.httpsCertFile = data.httpsCertFile;
  form.useRelay = data.useRelay;
  form.relays = [];
  // Object.assign(form, data);
  currentCluster.value = data.clusterHost;
  selectClusterNode(currentCluster.value);
  form.projectId = parseInt(data.projectId);
  relays.length = 0;
  data.relays.forEach(item => {
    delete item.id;
    delete item.ueInstanceId;
    relays.push(item);
  });

  console.log('relays', relays);
  delete form.connections;
  delete form.id;
  console.log(form);

  // currentCluster.value = form.clusterHost;
  // relays.length = 0;
  // relays.push(...form.relays);
};
// 确认按钮
const emit = defineEmits(['updateList']);
const confirm = () => {
  //同步relays数据
  form.relays = [...relays];
  console.log('submit form', form);
  post('/ueinstance/createInstance', form)
    .then(() => {
      emit('updateList');
    })
    .finally(() => {
      cancle();
    });
};
const relays = reactive([]);
const addRelay = () => {
  relays.push({
    stun: '',
    turn: '',
    relayUsername: '',
    relayPassword: '',
  });
};
const deleteRelay = index => {
  relays.splice(index, 1);
};
defineExpose({ dialogFormVisible, initCopyForm, initForm });
</script>

<style scoped>
.el-form {
  max-height: 60vh;
  overflow-y: auto;
  transition: 0.3s ease;
}
.relay {
  padding: 20px 100px 20px 0;
  border: 1px solid #ebeef5;
  border-radius: 5px;
  position: relative;
}
.relay_delete {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}
</style>
